package com.atguigu.tingshu.payment.config;

import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Configuration
@ConfigurationProperties(prefix="wechat.v3pay")
@Data
public class WxPayV3Config {

    private String appid;
    private String merchantId;
    private String privateKeyPath;
    private String merchantSerialNumber;
    private String apiV3key;
    private String notifyUrl;

    @Bean
    public RSAAutoCertificateConfig getConfig() throws IOException {
        // 方案1：使用classpath资源加载（推荐）
        Resource resource = new ClassPathResource("apiclient_key.pem");
        String privateKey = new String(Files.readAllBytes(Paths.get(resource.getURI())));

        return new RSAAutoCertificateConfig.Builder()
                .merchantId(merchantId)
                .merchantSerialNumber(merchantSerialNumber)
                .apiV3Key(apiV3key)
                .privateKey(privateKey) // 直接传入密钥内容
                .build();

        /* 方案2：使用绝对路径（需确保文件存在）
        return new RSAAutoCertificateConfig.Builder()
                .merchantId(merchantId)
                .privateKeyFromPath("src/main/resources/apiclient_key.pem")
                .merchantSerialNumber(merchantSerialNumber)
                .apiV3Key(apiV3key)
                .build();
        */
    }
}
